<template>
  <el-dialog :title="`${form.id?'修改':'添加'}用户`" :visible.sync="dialogVisible" @opened="dialogOpen">
    <el-form ref="form" :model="form" label-width="80px" size="small">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item prop="nickname" label="用户昵称">
            <el-input v-model="form.nickname"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="username" label="用户名称">
            <el-input v-model="form.username"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item prop="password" label="用户密码">
            <el-input v-model="form.password" type="password" suffix-icon="fa fa-lock"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="sex" label="用户性别">
            <el-input v-model="form.sex"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item prop="email" label="用户邮箱">
            <el-input v-model="form.email" suffix-icon="fa fa-envelope"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="mobilePhone" label="用户电话">
            <el-input v-model="form.mobilePhone" suffix-icon="fa fa-mobile-phone"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item prop="id" label="组织机构">
        <tree-select ref="deptTree" @change="changeParent"/>
      </el-form-item>
      <el-form-item prop="post" label="职务">
        <el-select v-model="form.jobCode" :placeholder="form.jobCode" style="width: 100%">
          <el-option
                  v-for="item in postList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="角色列表">
        <el-checkbox-group v-model="userRoleList" v-if="roleList && roleList.length">
          <el-checkbox v-for="role in roleList" :label="role.roleName" :key="role.id"/>
        </el-checkbox-group>
        <div v-else style="color:red;">没有角色信息</div>
      </el-form-item>
      <el-form-item class="from-bnts">
        <el-button type="primary" @click="submit">保存</el-button>
        <el-button @click="close">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>
<script>
  import userApi from "@/api/system/user";
  import deptApi from "@/api/system/dept";
  import roleApi from "@/api/system/role";
  import utils from '@/assets/utils/zhzf-util';
  import dictCache from "@/assets/utils/cache-dict-util";
  import TreeSelect from "@/views/comps/zhzf/tree-select";

  export default {
    name: "userEditForm",
    components: {TreeSelect},
    props: {
      value: Boolean
    },
    data() {
      return {
        loading: false,
        dialogVisible: false,
        form: {},
        // depts:[],
        treeList: [],
        userRoleList: [],
        roleList: [],
        postList: [],
      };
    },

    watch: {
      value(val) {
        this.dialogVisible = val;
      },
      dialogVisible(val) {
        this.$emit("input", val);
      }
    },
    methods: {
      changeParent(item) {
        this.form.orgCode = item.id;
        this.form.dept.id = item.id;
        this.getAndCheckedRole();
      },
      async getdepData(param) {
        this.dialogVisible = true;
        this.form = param.info;
        this.treeList = param.treeList;
      },
      async dialogOpen() {
        this.userRoleList=[];
        // this.form.dept='bdfd3fa348f14288abcc86e276a6b69b';//模拟用户所属机构
        // this.form.roles=[{roleName:'lupc5'},{roleName:'lupc8'}]//模拟用户角色列表

        if(!this.form.id){//点击添加时清除checkbox
            this.roleList = [];
        }
        if(!this.form.dept){
          this.form.dept={};
        }
        let userDept = {id:this.form.dept,name:this.form.dept.name}||{};//如果编辑，需要查找用户当前的机构信息
        this.$refs.deptTree.initPage(this.treeList, userDept.id ? userDept : {}, userDept.id ? [userDept.id] : [])
        if(this.form.dept){
          this.changeParent({id:this.form.dept.id})
        }
        let postListTmp = await dictCache.getDataList("0007"); //职务列表
        this.postList = postListTmp;
      },

      /**
       * 获取并反显角色
       * 1、根据用户所在机构，查询机构关联的角色列表
       * 2、查询用户关联的角色列表
       * 3、根据用户关联的角色，设置角色反选状态
       */
      async getAndCheckedRole() {
        let res = await deptApi.deptRole({id: this.form.dept.id});
        this.roleList = res.data;
        if (!this.roleList){
          utils.showTips(res.msg,res.ok);
        }else{
          this.roleList = this.roleList.filter(item => {
            return item && item.id
          });
        }
        //设置用户角色反选
        this.userRoleList = [];
        if (this.form.roles){
          this.form.roles.forEach(item=>{
            this.userRoleList.push(item.roleName)
          });
        }

      },
      submit() {
        this.$refs["form"].validate(async valid => {
          if (!valid) {
            return false;
          }
          this.loading = true;
          await this.saveUserInfo();
          // await this.saveUserRole();
          this.loading = false;
          this.dialogVisible = false;
          this.$emit("submit");
        });
      },
      /**
       * 设置用户角色信息
       */
      async saveUserRole() {
        let roleMap = {};
        if (this.roleList){
          this.roleList.forEach(item => {
            roleMap[item.roleName] = item.id;
          });
        }
        let roleIds = []
        this.userRoleList.forEach(item => {
          roleIds.push(roleMap[item]);
        });
        let data = {userId: this.form.id, roleIds: roleIds};
        await roleApi.assignUser(data);
      },
      /**
       * 设置用户基本信息
       */
      async saveUserInfo() {
        let time = new Date();
        this.form.createdDatetime = time.getTime();
        this.form.enabled = '0';
        this.form.emailValidated = '0';
        this.form.mobilePhoneValidated = '0';
        let roleMap = {};
        if (this.roleList){
          this.roleList.forEach(item => {
            roleMap[item.roleName] = item.id;
          });
        }
        let roleIds = [];
        this.userRoleList.forEach(item => {
          roleIds.push(roleMap[item]);
        });
        this.form.roles = roleIds;
        let method = this.form.id ? userApi.modUser : userApi.addUser;
        await method({...this.form, operateType: "11", realname: "11"})
      },
      close() {
        this.$refs["form"].resetFields();
        this.dialogVisible = false;
      }
    }
  };
</script>

